/**
 * @Author: Bobby
 * @Date: 2022-01-08 12:10:36
 * @LastEditTime: 2022-03-17 09:14:59
 * @LastEditors: Bobby
 * @Description:
 * @FilePath: \wms-v2\src\common\project\router\index.js
 * @CIMC-V2
 */
/**
 * @description router全局配置，如有必要可分文件抽离，其中asyncRoutes只有在intelligence模式下才会用到
 */
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import { authentication, isHashRouterMode, publicPath } from '@project/config'
import { constantRoutes as projectConstantRoutes, asyncRoutes as projectAsyncRoutes } from '@project/router'
import Layout from '@/vui/layouts'
import { translateTitle } from '@/utils/i18n'
//固定路由
export const constantRoutes = [
  {
    path: '/403',
    name: '403',
    component: () => import('@/components/403'),
    meta: {
      hidden: true,
    },
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/components/404'),
    meta: {
      hidden: true,
    },
  },
  ...projectConstantRoutes,
]

// 路由
export const asyncRoutes = [
  //匹配不到 就跳转到404
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
    name: 'NotFound',
    meta: {
      hidden: true,
    },
  },
  ...projectAsyncRoutes,
]

export const dashboardRoute = [
  {
    path: '/',
    name: 'Dashboard',
    component: Layout,
    meta: {
      breadcrumbHidden: true,
      levelHidden: true,
    },
    children: [
      {
        path: 'dashboard',
        name: 'dashboard',
        component: () => import(`@/components/home_${process.env.VUE_APP_BuildProjectType}`),
        meta: {
          title: translateTitle('Base.baseAdmin.控制台'),
          icon: 'dashboard-3-fill',
          noClosable: true,
        },
      },
    ],
  },
]

const router = createRouter({
  history: isHashRouterMode ? createWebHashHistory(publicPath) : createWebHistory(publicPath),
  routes: constantRoutes,
})

// 递归查找子路由
function fatteningRoutes(routes) {
  return routes.flatMap((route) => {
    return route.children ? fatteningRoutes(route.children) : route
  })
}

// 添加
function addRouter(routes) {
  routes.forEach((route) => {
    if (!router.hasRoute(route.name)) router.addRoute(route)
    if (route.children) addRouter(route.children)
  })
}

// 重置
export function resetRouter(routes = constantRoutes) {
  routes.map((route) => {
    if (route.children) {
      route.children = fatteningRoutes(route.children)
    }
  })
  router.getRoutes().forEach((route) => {
    const routeName = route.name
    router.hasRoute(routeName) && router.removeRoute(routeName)
  })
  addRouter(routes)
}

export function setupRouter(app) {
  if (authentication === 'intelligence') addRouter(asyncRoutes)
  app.use(router)
  return router
}

export default router
